package com.rong.ruiji.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.rong.ruiji.common.BaseContext;
import com.rong.ruiji.common.R;
import com.rong.ruiji.entity.Category;
import com.rong.ruiji.entity.Employee;
import com.rong.ruiji.service.CategoryService;
import com.rong.ruiji.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService ;

    /**
     * 新增菜品或套餐分类
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Category category) {
        Long empId =(Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);
        categoryService.save(category);

        return R.success("新增分类成功...");
    }

    @GetMapping("/page")
    public R<Page> page( @RequestParam int page, @RequestParam int pageSize) {
        //构造分页构造器
        Page<Category> pageInfo = new Page<>(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper();
        //添加排序条件
        queryWrapper.orderByDesc(Category::getId);
        //执行查询
        categoryService.page(pageInfo,queryWrapper);



        return R.success(pageInfo);
    }

    /**
     * 根据id删除分类
     * @param ids
     * @return
     */
    @DeleteMapping()
    public R<String> delete(@RequestParam Long ids) {
        categoryService.remove(ids);
//        log.info(String.valueOf(ids));
//        categoryService.removeById(ids);
        return R.success("删除成功");
    }

    /**
     * 根据id修改分类信息
     * @param category
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request,@RequestBody Category category) {
        Long empId = (Long) request.getSession().getAttribute("employee");
        BaseContext.setCurrentId(empId);
        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(category.getType() != null,Category::getType,category.getType());
        lambdaQueryWrapper.orderByDesc(Category::getSort);
        List<Category> categoryList = categoryService.list(lambdaQueryWrapper);
        return R.success(categoryList);
    }

}
